package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

// 该类会被自动调用 AuthenticationManager（AdminServiceImpl中） 自动调用传递过来 Authentication 对象封装的用户名和密码
// 再调用 loadUserByUsername() 方法通过传递过来的用户名查询数据库中匹配的数据，封装成 UserDetails 对象由Security框架自动判断
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 从数据库中通过前端登录界面输入的用户名查询匹配项
        log.debug("用户名：{}", s);
        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(s);

        // 如果查不到就返回null
        if (loginInfo == null) {
            log.debug("此用户名没有匹配的用户数据，将返回null");
            return null;
        }

        log.debug("用户名匹配成功！准备返回此用户名匹配的UserDetails类型的对象");
        // 如果用户名匹配，则向 Spring Security 框架返回一个 UserDetails ，框架自动判断账号状态确定是否登录成功
//        UserDetails userDetails = User.builder()
//                .username(loginInfo.getUsername())
//                .password(loginInfo.getPassword())
//                .disabled(loginInfo.getEnable() == 0) // 账号状态是否禁用 (loginInfo.getEnable()==0 ? true : false)
//                .accountLocked(false) // 账号状态是否锁定
//                .accountExpired(false) // 账号状态是否过期
//                .credentialsExpired(false) // 账号的凭证是否过期
//                .authorities("这是一个临时使用的山寨的权限！！！") // 权限
//                .build();
        List<String> permissions = loginInfo.getPermissions();
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }


        AdminDetails userDetails = new AdminDetails(loginInfo.getId(), loginInfo.getUsername(), loginInfo.getPassword(), loginInfo.getEnable() == 1, authorities);
        log.debug("即将向Spring Security返回UserDetails类型的对象：{}", userDetails);
        return userDetails;
    }
}
